package com.basic.modules.ykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.basic.common.utils.ParamsModel;
import com.basic.common.utils.ParamUtils;
import com.basic.modules.sys.service.SysUserService;
import com.basic.modules.ykf.entity.RuleItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.utils.PageUtils;
import com.basic.common.utils.Query;

import com.basic.modules.ykf.dao.YkfShopDistributeRuleDao;
import com.basic.modules.ykf.entity.YkfShopDistributeRuleEntity;
import com.basic.modules.ykf.service.YkfShopDistributeRuleService;

import java.util.List;


@Service("ykfShopDistributeRuleService")
public class YkfShopDistributeRuleServiceImpl extends ServiceImpl<YkfShopDistributeRuleDao, YkfShopDistributeRuleEntity> implements YkfShopDistributeRuleService {

    @Autowired
    private SysUserService userService;

    @Override
    public PageUtils queryPage(ParamsModel<YkfShopDistributeRuleEntity> params) {
        if (ObjectUtil.isEmpty(params.getSort()) || StrUtil.isBlank(params.getSort().getSidx()) || StrUtil.isBlank(params.getSort().getOrder())) {
            ParamsModel.SortParams sortParams = new ParamsModel.SortParams();
            sortParams.setSidx("createTime");
            sortParams.setOrder("desc");
            params.setSort(sortParams);
        }
        QueryWrapper<YkfShopDistributeRuleEntity> queryWrapper = ParamUtils.createQueryWrapperByDefaultSort(params);
        if (StrUtil.isNotBlank(params.getCondition().getKeyword())) {
            queryWrapper.lambda().like(YkfShopDistributeRuleEntity::getRuleName, params.getCondition().getKeyword());
        }

        IPage<YkfShopDistributeRuleEntity> page = this.page(
                new Query<YkfShopDistributeRuleEntity>().getPage(BeanUtil.beanToMap(params.getPage())),
                queryWrapper
        );
        if (ObjectUtil.isNotEmpty(page) && ObjectUtil.isNotEmpty(page.getRecords())) {
            for (YkfShopDistributeRuleEntity record : page.getRecords()) {
                List<RuleItem> list = JSONUtil.toList(JSONUtil.parseArray(record.getRuleJson()), RuleItem.class);
                record.setRuleList(list);
            }
        }
        return new PageUtils(page);
    }

}
